import datetime
import MySQLdb
import SocketServer.logger as logger
from SocketServer.config import config as CF


def mysql_connect_creat():
    '''
    初始化MYSQL连接池
    :return:
    '''
    return MySQLdb.connect(CF()['host'], CF()['username'], CF()['password'], CF()['dbname'], charset='utf8')


def init_device(device, bednum, init_cap, init_factor, init_speed):
    '''
    注册设备
    :param device: ID 设备 ID
    :param bednum: bn 病患床号
    :param init_cap:ic 输液规格
    :param init_factor:if 滴系数
    :param init_speed:is 最佳滴速
    :return:
    '''
    logger.loginfo("信息%s" % [device, bednum, init_cap, init_factor, init_speed])
    cursor = mysql_connect_creat().cursor()
    cursor.execute("SELECT bed_id FROM `api_bed` WHERE bed_id='%s'" % bednum)
    data = cursor.fetchone()
    if (data != None):
        logger.logerror("床位存在")
        sql = "SELECT device FROM `api_devices` WHERE device=%d" % device
        cursor.execute(sql)
        device_select = cursor.fetchall()
        if len(device_select) != 0:
            logger.logerror("%d设备存在" % device)
            sql = "SELECT device,bednum FROM `api_devices` WHERE bednum='%s'" % bednum
            bed_device = cursor.execute(sql)
            print("床位",bednum, "未被占用" if bed_device == 0 else "被占用",bed_device)
            if bed_device == 0:
                sql = "UPDATE `api_devices` SET bednum='%s',init_cap=%d,init_factor=%d,init_speed=%d,init_time=CURTIME(),alarm_time='00:00:00', is_init=%d WHERE device=%d" \
                      % (bednum, init_cap, init_factor, init_speed, 1, device)
                cursor.execute(sql)
            else:
                return 0
        else:
            cursor.execute(
                "INSERT INTO `api_devices` (device,alarm,battery,value_speed,value_cap,value_time,bednum,init_cap,init_factor,init_speed,alarm_time) VALUES (%d,%d,%f,%d,%f,'%s','%s',%d,%d,%d,'00:00:00')" % (
                    device, 1, 1, 1, 1, 1, bednum, init_cap, init_factor,
                    init_speed))
        return 1
    else:
        logger.loginfo("没有此床位")
        return 0


def update_device_info(device, alarm=0, battery=1, value_speed=1, value_cap=1, value_time=99, bednum='0', init_cap=0,
                       init_factor=0,
                       init_speed=99):
    try:
        cursor = mysql_connect_creat().cursor()
        cursor.execute("SELECT device FROM `api_devices` WHERE `device`=%d" % device);
        if len(cursor.fetchone()) == 0:
            cursor.execute(
                "INSERT INTO `api_devices` (device,alarm,battery,value_speed,value_cap,value_time,bednum,init_cap,init_factor,init_speed) VALUES (%d,%d,%f,%d,%f,'%s','%s',%d,%d,%d)" % (
                    device, alarm, battery, value_speed, value_cap, value_time, bednum, init_cap, init_factor,
                    init_speed))
        else:
            cursor.execute(
                "UPDATE `api_devices` SET alarm=%d,battery=%f,value_speed=%d,value_cap=%d,value_time=%s,bednum=%s,init_cap=%d,init_factor=%d,init_speed=%d" % (
                    device, alarm, battery, value_speed, value_cap, value_time, bednum, init_cap, init_factor,
                    init_speed))
    except Exception as e:
        logger.logerror(e)


def delete_device(device):
    '''
    注销设备
    :param device: 设备ID
    :return:
    '''
    device = int(device)
    try:
        mysql_connect_creat().cursor().execute("DELETE FROM `api_devices` WHERE `device`=%d" % (device));
    except Exception as e:
        logger.logerror("设备注销异常")
        return 0
    return 1


def heart_beat(device, alarm):
    '''
    心跳处理
    :param device:
    :param alarm:
    :return:
    '''
    cursor = mysql_connect_creat().cursor()
    device_info = cursor.execute("SELECT device,is_init,bednum FROM `api_devices` WHERE device=%d" % device)
    # exit()
    if device_info == 0:
        sql = "INSERT INTO `api_devices` (device,bednum,init_cap,init_factor,init_speed,value_time,init_time,alarm_time,alarm,battery,value_speed,value_cap,is_init) VALUES (%d ,'%s',%d,%d,%d,0,'%s','23:00:00',%d,%d,%d,%d,%d)" % (
            device, -1, 0, 0, 0, (datetime.datetime.now() + datetime.timedelta(hours=8)).strftime("%H:%M:%S"), 0, 0, 0,
            0, 0)
        cursor.execute(sql)
    if alarm != 0:
        cursor.execute("SELECT alarm FROM `api_devices` WHERE `device`=%d" % device)
        device_info = cursor.fetchone()
        if device_info[0] == 0:
            sql = "UPDATE  `api_devices` SET alarm_time='%s' WHERE `device`=%d" % (
                (datetime.datetime.now() + datetime.timedelta(hours=8)).strftime("%H:%M:%S"), device)
            try:
                mysql_connect_creat().cursor().execute(sql)
            except Exception as e:
                logger.logerror("心跳处理时间处理异常")
    sql = "UPDATE  `api_devices` SET alarm=%d WHERE `device`=%d" % (alarm, device)
    try:
        mysql_connect_creat().cursor().execute(sql)
    except Exception as e:
        logger.logerror("心跳处理警报处理异常")


def device_state(device, value_speed, value_cap, value_time):
    '''
    状态监测处理
    :param device: 设备ID
    :param value_speed: 滴速
    :param value_cap: 剩余液量
    :param value_time: 剩余时间
    :return:
    '''
    sql = "UPDATE  `api_devices` SET value_speed=%d,value_cap=%d,value_time=%d WHERE `device`=%d" % (
        value_speed, value_cap, value_time, device)
    try:
        mysql_connect_creat().cursor().execute(sql)
    except Exception as e:
        logger.logerror("设备状态监测处理异常")


def update_battery(device, battery):
    '''
    电池余量处理
    :param device: 设备ID
    :param battery: 电池余量
    :return:
    '''
    sql = "UPDATE  `api_devices` SET battery=%d WHERE `device`=%d" % (battery, device)
    try:
        mysql_connect_creat().cursor().execute(sql)
    except Exception as e:
        logger.logerror("设备电池余量处理异常")
